<?php
/*core function of each module, act's like controller*/
function useModel($page_title, $page_keywords, $page_description, $content, $page_template_id, $page_locked){
	session_start();
	if(!$_POST){
			//session_start();
			$getcontent = "calculateContent". $content;
			
			$page_visible = checkStatus();
			//check if page closed, etc catalogue
			if($page_visible){
				/*executing code and write to buffer content */
				ob_start();
				ob_implicit_flush(0);
				$getcontent();   
				$site_templ_content = ob_get_contents();
				ob_end_clean();
				
				/*output content*/
				return displayTemplated($page_title, $page_keywords, $page_description, $site_templ_content, $page_template_id, $page_locked);//return site
			}
			else{
				return displayError(404, $route);//return error
			}
	}
	else{
		$getcontent = $content. "Content";
		/*executing code and write to buffer content */
		ob_start();
		ob_implicit_flush(0);
		$getcontent();   
		$site_templ_content = ob_get_contents();
		ob_end_clean();
		
		/*output content*/
		return displayTemplated($page_title, $page_keywords, $page_description, $site_templ_content, $page_template_id, $page_locked);//return site
	}
}
//subcontroller
function checkStatus(){
	switch($_GET["route"]){
		default:
			return true;
		break;
		case "catalogue/":
			$query = "SELECT cat_visible FROM kpulse_categories WHERE cat_link='". addslashes($_GET["catalogue"]) ."'";
			$result = mysql_query($query) or die(mysql_error());
			if(mysql_num_rows($result) > 0){
				list($visible) = mysql_fetch_row($result);
				return $visible;
			}
			else{
				return false;	
			}	
		break;
		case "view/":
			$_GET["view"] = substr($_GET["view"],  0, -1);
			$query = "SELECT product_publicate FROM kpulse_products WHERE product_id='". $_GET["view"] ."'";
			$result = mysql_query($query) or die(mysql_error());
			if(mysql_num_rows($result) > 0){
				list($visible) = mysql_fetch_row($result);
				return $visible;	
			}
			else{
				return false;	
			}
		break;
		case "producer/":
			$query = "SELECT producer_id FROM kpulse_producers WHERE producer_link='". addslashes($_GET["producer"]) ."'";
			$result = mysql_query($query) or die(mysql_error());
			if(mysql_num_rows($result) > 0){
				return true;	
			}
			else{
				return false;	
			}	
		break;
	}	
}

//mainpage
function calculateContentMainpage(){
		$query = "SELECT node.cat_id, node.cat_name, node.cat_link, (COUNT(parent.cat_name) - (sub_tree.depth + 1)) AS depth
		FROM kpulse_categories AS node,
			kpulse_categories AS parent,
			kpulse_categories AS sub_parent,
			(
				SELECT node.cat_name, (COUNT(parent.cat_name) - 1) AS depth
				FROM kpulse_categories AS node,
				kpulse_categories AS parent
				WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
				AND node.cat_name = 'ROOT'
				GROUP BY node.cat_name
				ORDER BY node.cat_lft
			)AS sub_tree
		WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
			AND node.cat_lft BETWEEN sub_parent.cat_lft AND sub_parent.cat_rgt
			AND sub_parent.cat_name = sub_tree.cat_name
		GROUP BY node.cat_name
		HAVING depth = 1
		ORDER BY node.cat_lft";
	
	$result = mysql_query($query) or die(mysql_error());

	while($row = mysql_fetch_assoc($result)){
		echo "<div class=\"fmenu\">
					<a href=\"catalogue/". $row["cat_link"] ."\"><img alt=\"". $row["cat_name"] ."\" src=\"/images/menu/". $row["cat_id"] .".jpg\"></a><br>
					<a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>
				</div>";
	}
		
} 

//catalogue
function calculateContentCatalogue(){
	//Full menu
	$query = "SELECT node.cat_name, node.cat_link, (COUNT(parent.cat_name) - 1) AS depth
	FROM kpulse_categories AS node,
	kpulse_categories AS parent
	WHERE node.cat_lft BETWEEN parent.cat_lft
	AND parent.cat_rgt
	AND node.cat_visible=1
	GROUP BY node.cat_link
	ORDER BY node.cat_lft";
	$result = mysql_query($query) or die(mysql_error());

	//child - wether child or not element
	echo "<ul id=\"catalog-menu\">";
	$first = true;
	$child = false;
	while($row = mysql_fetch_assoc($result)){
		if($row["depth"] > 0 && $row["depth"] < 3){
			if($row["depth"]==1 && !$child && $first){
				echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
				$first = false;
			}
			elseif($row["depth"]==1 && !$child && !$first){
				echo "</li><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
			}
			elseif($row["depth"]==1 && $child){
				echo "</ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
				$child = false;
			}
			elseif($row["depth"]==2 && !$child){
				echo "<ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
				$child = true;
			}
			elseif($row["depth"]==2 && $child){
				echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
			}
		}
	}
	echo "</li></ul></li></ul>";
	
	
	
	
	//Catalogue link
	if(!isset($_GET["catalogue"]) || $_GET["catalogue"]==""){
		$_GET["catalogue"] = "all/";
	}
	
	//?more option
	if(!isset($_GET["next"]) || $_GET["next"]==""){
		$_GET["next"]="0";
	}
	else{
		$_GET["next"] = substr($_GET["next"],  0, -1);	
	}
	//counting result rows
	$query = "SELECT SQL_NO_CACHE kpulse_products.*
	FROM kpulse_categories AS parent,  kpulse_categories AS node,
	kpulse_products
	WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
	AND parent.cat_link = '". addslashes($_GET["catalogue"]) ."'
	AND node.cat_id = kpulse_products.product_cat_id
	AND node.cat_visible=1
	AND kpulse_products.product_publicate=1
	ORDER BY parent.cat_lft";
	$qresult = mysql_query($query) or die(mysql_error());
	
	$quantity = mysql_num_rows($qresult);
	if($quantity > 20){
		echo "<ul class=\"nextlinks\">";
		if(isset($_GET["next"]) && $_GET["next"]!="" && $_GET["next"] > 1){
			echo "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". ($_GET["next"] - 20) ."\">&#x21e6;Назад</a></li>";
		}
		$n=1;
		for($i=0; $i< $quantity; $i=$i+20){
			if($_GET["next"] <= $quantity){
				echo $_GET["next"]!= $i ? "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". $i ."\">". $n ."</a></li>" : "<li>". $n ."</li>";
				$n++;
			}
		}
		if(isset($_GET["next"]) && $_GET["next"]!="" && $quantity > ($_GET["next"] +20)){
			echo "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". ($_GET["next"] + 20) ."\">Вперед&#x21e8;</a></li>";
		}
		echo "</ul><br>";
	}
	//showing subcats
	$query = "SELECT node.cat_name, node.cat_link, (COUNT(parent.cat_name) - (sub_tree.depth + 1)) AS depth
		FROM kpulse_categories AS node,
			kpulse_categories AS parent,
			kpulse_categories AS sub_parent,
			(
				SELECT node.cat_name, (COUNT(parent.cat_name) - 1) AS depth
				FROM kpulse_categories AS node,
				kpulse_categories AS parent
				WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
				AND node.cat_link = '". $_GET["catalogue"] ."'
				GROUP BY node.cat_name
				ORDER BY node.cat_lft
			)AS sub_tree
		WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
			AND node.cat_lft BETWEEN sub_parent.cat_lft AND sub_parent.cat_rgt
			AND sub_parent.cat_name = sub_tree.cat_name
			AND node.cat_visible=1
		GROUP BY node.cat_name
		HAVING depth = 1
		ORDER BY node.cat_lft;";
	$result = mysql_query($query) or die(mysql_error());
	echo "<div id=\"subcats\">";
	while($row = mysql_fetch_assoc($result)){
		?>
			<a href="catalogue/<?php echo $row["cat_link"]?>"><?php echo $row["cat_name"]?></a>
		<?php 
	}
	echo "</div><br style=\"clear:both;\">";
	
	
	
	$query = "SELECT SQL_NO_CACHE kpulse_products.*,
								 kpulse_photos.photo_tiny_img,
								 kpulse_producers.producer_name,
								 kpulse_producers.producer_link
	FROM kpulse_categories AS parent, kpulse_categories AS node,
	kpulse_products, kpulse_photos, kpulse_producers
	WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
	AND parent.cat_link = '". addslashes($_GET["catalogue"]) ."'
	AND node.cat_id = kpulse_products.product_cat_id 
	AND kpulse_photos.photo_product_id = kpulse_products.product_id
	AND kpulse_photos.photo_cat_logo=1
	AND kpulse_products.product_publicate=1
	AND kpulse_producers.producer_id = kpulse_products.product_producer_id
	ORDER BY parent.cat_lft LIMIT ". $_GET["next"] .",20";
	//echo $query;die;
	$result = mysql_query($query) or die(mysql_error());
	
	echo "<table id=\"products-list\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" >";
	while($row = mysql_fetch_assoc($result)){
	?>
		<tr>
			<td colspan="3">
				<h2 class="product_title"><a title="Перейти к товару" href="view/<?php echo $row["product_id"] ?>" class="moreh"><?php echo $row["product_name"]?></a></h2>
			</td>
		</tr>
		<tr class="product-desc">
			<td class="first-row">
				<a href="/view/<?php echo $row["product_id"]?>" class="imglink">
					<img alt="<?php echo $row["product_name"]?>" src="images/product_images/tiny/<?php echo $row["photo_tiny_img"]?>">
				</a>
				<br>
				<a href="/view/<?php echo $row["product_id"]?>" class="more">Подробнее</a>
			</td>
			<td class="second-row">
				<?php
					if($row["product_display_producer"]){
						echo "<p class=\"producer\">Производитель: <a class=\"moreimg\" href=\"producer/". $row["producer_link"] ."\" title=\"". $row["producer_name"] ."\">". $row["producer_name"] ."</a><a></a></p>";		
					}
				
				 echo $row["product_short_des"];
				 ?>
			</td>
			<td class="third-row">
				<div class="buy-container-list">
					<p>Цена: <?php echo (int)($row["product_price"])?> грн.</p>
					<form name="addproduct" method="post" enctype="application/x-www-form-urlencoded" action="cart/">
						<label for="quantity-alt">Кол-во</label>
						<input name="id" type="hidden" value="<?php echo $row["product_id"] ?>">
						<input class="quantity-alt" id="quantity-alt" name="quantity" type="text" value="1" />
						<input type="submit" class="buy-me" value="">
					</form>
				</div>
			</td>
		</tr>
	 <?php
	}
	echo "</table>";
	if($quantity > 20){
		echo "<ul class=\"nextlinks\">";
		if(isset($_GET["next"]) && $_GET["next"]!="" && $_GET["next"] > 1){
			echo "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". ($_GET["next"] - 20) ."\">&#x21e6;Назад</a></li>";
		}
		$n=1;
		//for($i=0; ($i - 20)<= $quantity; $i=$i+20){
		for($i=0; $i< $quantity; $i=$i+20){
			if($_GET["next"] <= $quantity){
				echo $_GET["next"]!= $i ? "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". $i ."\">". $n ."</a></li>" : "<li>". $n ."</li>";
				$n++;
			}
		}
		if(isset($_GET["next"]) && $_GET["next"]!="" && $quantity > ($_GET["next"] +20)){
			echo "<li><a href=\"". domain_path ."catalogue/". $_GET["catalogue"] ."&next=". ($_GET["next"] + 20) ."\">Вперед&#x21e8;</a></li>";
		}
		echo "</ul><br>";
	}
}

//Products
function calculateContentView(){

	//Full menu
	$query = "SELECT node.cat_name, node.cat_link, (COUNT(parent.cat_name) - 1) AS depth
	FROM kpulse_categories AS node,
	kpulse_categories AS parent
	WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
	GROUP BY node.cat_link
	ORDER BY node.cat_lft";
	$result = mysql_query($query) or die(mysql_error());

	//child - wether child or not element
	echo "<ul id=\"catalog-menu\">";
	$first = true;
	$child = false;
	while($row = mysql_fetch_assoc($result)){
		if($row["depth"] > 0 && $row["depth"] < 3){
			if($row["depth"]==1 && !$child && $first){
				echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
				$first = false;
			}
			elseif($row["depth"]==1 && !$child && !$first){
				echo "</li><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
			}
			elseif($row["depth"]==1 && $child){
				echo "</ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
				$child = false;
			}
			elseif($row["depth"]==2 && !$child){
				echo "<ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
				$child = true;
			}
			elseif($row["depth"]==2 && $child){
				echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
			}
		}
	}
	echo "</li></ul></li></ul>";
	
	
	$query = "SELECT SQL_NO_CACHE product_name, product_description, product_price, product_code_number, kpulse_producers.producer_name, product_description_index
	FROM kpulse_products,  kpulse_producers
	WHERE product_id=". $_GET["view"] ." 
	AND kpulse_producers.producer_id=kpulse_products.product_producer_id";
	//echo $query;
	$result = mysql_query($query) or die(mysql_error());
	list($name, $description, $price, $code, $producer, $indexed) = mysql_fetch_row($result);
	
	$query = "SELECT photo_small_img,
	photo_large_img,
	photo_tiny_img,
	photo_alt FROM kpulse_photos
	WHERE photo_product_id=". $_GET["view"] ."
	ORDER BY photo_cat_logo DESC";
	$imgresult = mysql_query($query) or die(mysql_error());
	
	$i=0;
	while($imgrow = mysql_fetch_assoc($imgresult)){
		$img_arr[$i]["tiny"] = $imgrow["photo_tiny_img"];
		$img_arr[$i]["small"] = $imgrow["photo_small_img"];
		$img_arr[$i]["large"] = $imgrow["photo_large_img"];
		$img_arr[$i]["img_name"] = $imgrow["photo_alt"];
		$i++;
	}
	
	?>
	<div id="product-content">
		<div id="image-frame">
		<img id="arrow-left" src="images/icons/arrow-left.gif" alt="">
			<?php
			if(count($img_arr) > 0){ 
				foreach($img_arr as $value){
					echo "<div class=\"showme image-preview\"><p>". $value["img_name"] ."</p><a  id=\"large-". $value["large"] ."\" href=\"images/product_images/large/". $value["large"] ."\" target=\"_blank\"><img src=\"images/product_images/small/". $value["small"] ."\" alt=\"". $value["img_name"] ."\"></a></div>";
				}
			}
			?>
			<img id="arrow-right" src="images/icons/arrow-right.gif" alt="">
			<div id="image-list">
			<?php 
			if(count($img_arr) > 1){
				foreach($img_arr as $value){
					echo "<a id=\"". $value["large"] ."\"><img src=\"images/product_images/tiny/". $value["tiny"] ."\" alt=\"". $value["img_name"] ."\"></a>";
				}
			}
			?>
			</div>
		</div>
	<div class="buy-container">
		<p>Цена: <?php echo (int)($price)?> грн.</p>
		
		<form name="addproduct" method="post" enctype="application/x-www-form-urlencoded" action="cart/">
			<label for="quantity">Кол-во</label>
			<input name="id" type="hidden" value="<?php echo $_GET["view"] ?>">
			<input class="quantity" id="quantity" name="quantity" type="text" value="1" />
			<input type="submit" class="buy-me" value="">
		</form>
	</div>
	<?php 
		echo $indexed ? "<div>" : "<div CONTENT=\"NOINDEX\">";	
	?>
	<h2><?php echo $name ?></h2>
	<p>
		<?php
			if(isset($code) && $code!=""){
				echo "Артикул:&nbsp;".$code;
			}
		?>
	</p>
	<p>
		<?php echo $description?>
	</p>
	</div>
	<div class="buy-container-alt">
		<p>Цена: <?php echo (int)($price)?> грн.</p>
		<form name="addproduct" method="post" enctype="application/x-www-form-urlencoded" action="cart/">
			<label for="quantity-alt">Кол-во</label>
			<input name="id" type="hidden" value="<?php echo $_GET["view"] ?>">
			<input class="quantity-alt" id="quantity-alt" name="quantity" type="text" value="1" />
			<input type="submit" class="buy-me" value="">
		</form>
	</div>
	</div>
<?php	
}

//PRODUCERS
function calculateContentProducerShow(){
	if(isset($_GET["producer"]) && $_GET["producer"]!=""){
		//Full menu
		$query = "SELECT node.cat_name, node.cat_link, (COUNT(parent.cat_name) - 1) AS depth
		FROM kpulse_categories AS node,
		kpulse_categories AS parent
		WHERE node.cat_lft BETWEEN parent.cat_lft AND parent.cat_rgt
		GROUP BY node.cat_link
		ORDER BY node.cat_lft";
		$result = mysql_query($query) or die(mysql_error());
	
		//child - wether child or not element
		echo "<ul id=\"catalog-menu\">";
		$first = true;
		$child = false;
		while($row = mysql_fetch_assoc($result)){
			if($row["depth"] > 0 && $row["depth"] < 3){
				if($row["depth"]==1 && !$child && $first){
					echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
					$first = false;
				}
				elseif($row["depth"]==1 && !$child && !$first){
					echo "</li><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
				}
				elseif($row["depth"]==1 && $child){
					echo "</ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a>";
					$child = false;
				}
				elseif($row["depth"]==2 && !$child){
					echo "<ul><li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
					$child = true;
				}
				elseif($row["depth"]==2 && $child){
					echo "<li><a href=\"catalogue/". $row["cat_link"] ."\">". $row["cat_name"] ."</a></li>";
				}
			}
		}
		echo "</li></ul></li></ul>";
		
		
			
		//?more option
		if(!isset($_GET["next"]) || $_GET["next"]==""){
			$_GET["next"]="0";
		}
		else{
			$_GET["next"] = substr($_GET["next"],  0, -1);	
		}
		//counting result rows
		$query = "SELECT SQL_NO_CACHE kpulse_products.*
		FROM kpulse_products, kpulse_producers
		WHERE kpulse_producers.producer_link='". addslashes($_GET["producer"]) ."'
		AND kpulse_producers.producer_id=kpulse_products.product_producer_id";
		
		$qresult = mysql_query($query) or die(mysql_error());
		
		$quantity = mysql_num_rows($qresult);
		
		if($quantity > 20){
			echo "<ul class=\"nextlinks\">";
			if(isset($_GET["next"]) && $_GET["next"]!="" && $_GET["next"] > 1){
				echo "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". ($_GET["next"] - 20) ."\">&#x21e6;Назад</a></li>";
			}
			$n=1;
			//for($i=0; ($i - 20)<= $quantity; $i=$i+20){
			for($i=0; $i<= $quantity; $i=$i+20){
				if($_GET["next"] <= $quantity){
					echo $_GET["next"]!= $i ? "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". $i ."\">". $n ."</a></li>" : "<li>". $n ."</li>";
					$n++;
				}
			}
			if(isset($_GET["next"]) && $_GET["next"]!="" && $quantity > ($_GET["next"] +20)){
				echo "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". ($_GET["next"] + 20) ."\">Вперед&#x21e8;</a></li>";
			}
			echo "</ul><br>";
		}
		
		$query = "SELECT SQL_NO_CACHE kpulse_products.*, kpulse_photos.photo_tiny_img
		FROM kpulse_products, kpulse_photos, kpulse_producers
		WHERE kpulse_photos.photo_product_id = kpulse_products.product_id
		AND kpulse_photos.photo_cat_logo=1
		AND kpulse_producers.producer_link='". addslashes($_GET["producer"]) ."'
		AND kpulse_products.product_producer_id=kpulse_producers.producer_id
		LIMIT ". $_GET["next"] .",20";
		//echo $query;die;
		$result = mysql_query($query) or die(mysql_error());
		
		echo "<table id=\"products-list\">";
		while($row = mysql_fetch_assoc($result)){
		?>
			<tr>
				<td colspan="3">
					<h2 class="product_title"><a title="Перейти к товару" href="/view/<?php echo $row["product_id"] ?>" class="moreh"><?php echo $row["product_name"]?></a></h2>
				</td>
			</tr>
			<tr class="product-desc">
				<td class="first-row">
					<a href="/view/<?php echo $row["product_id"]?>" class="imglink">
						<img alt="<?php echo $row["product_name"]?>" src="/images/product_images/tiny/<?php echo $row["photo_tiny_img"]?>">
					</a>
					<br>
					<a href="/view/<?php echo $row["product_id"]?>" class="more">Подробнее</a>
				</td>
				<td class="second-row">
					<?php echo $row["product_short_des"]?>
				</td>
				<td class="third-row">
					<div class="buy-container-list">
						<p>Цена: <?php echo (int)($row["product_price"])?> грн.</p>
						<form name="addproduct" method="post" enctype="application/x-www-form-urlencoded" action="cart/">
							<label for="quantity-alt">Кол-во</label>
							<input name="id" type="hidden" value="<?php echo $row["product_id"] ?>">
							<input class="quantity-alt" id="quantity-alt" name="quantity" type="text" value="1" />
							<input type="submit" class="buy-me" value="">
						</form>
					</div>
				</td>
			</tr>
		 <?php
		}
		echo "</table>";
		if($quantity > 20){
			echo "<ul class=\"nextlinks\">";
			if(isset($_GET["next"]) && $_GET["next"]!="" && $_GET["next"] > 1){
				echo "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". ($_GET["next"] - 20) ."\">&#x21e6;Назад</a></li>";
			}
			$n=1;
			//for($i=0; ($i - 20)<= $quantity; $i=$i+20){
			for($i=0; $i<= $quantity; $i=$i+20){
				if($_GET["next"] <= $quantity){
					echo $_GET["next"]!= $i ? "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". $i ."\">". $n ."</a></li>" : "<li>". $n ."</li>";
					$n++;
				}
			}
			if(isset($_GET["next"]) && $_GET["next"]!="" && $quantity > ($_GET["next"] +20)){
				echo "<li><a href=\"". domain_path ."producer/". $_GET["producer"] ."&next=". ($_GET["next"] + 20) ."\">Вперед&#x21e8;</a></li>";
			}
			echo "</ul><br>";
		}
	}
}

//CART
function calculateContentCart(){
	//remove product
	if(isset($_GET["remove"]) && $_GET["remove"]!=""){
		$_GET["remove"] = (int)$_GET["remove"];
		if(is_int($_GET["remove"])){
			if(isset($_SESSION["cart"][$_GET["remove"]])){
				unset($_SESSION["cart"][$_GET["remove"]]);
			}
			if(count($_SESSION["cart"]) < 1){
				unset($_SESSION["cart"]);
			}
		}
	}

	if(isset($_SESSION["cart"]) && $_SESSION["cart"]!=""){
		//print_r($_SESSION["cart"]);
		$i=0;
		foreach($_SESSION["cart"] as $key => $value){
			$i++;
			//first product
			//echo $i;
			if($i<2){
				$query = "SELECT product_id, product_name, product_code_number, product_price, kpulse_photos.photo_tiny_img as image FROM kpulse_products, kpulse_photos WHERE product_id=". $key ." AND product_id=kpulse_photos.photo_product_id AND photo_cat_logo=1";
			}
			else{
				$query .= " UNION SELECT product_id, product_name, product_code_number, product_price, kpulse_photos.photo_tiny_img FROM kpulse_products, kpulse_photos WHERE product_id=". $key . " AND product_id=kpulse_photos.photo_product_id AND photo_cat_logo=1";
			}
		}
		//echo $query;die();
		$result = mysql_query($query) or die(mysql_error());
		?>
		<form id="order-form" name="order-form" method="post" enctype="application/x-www-form-urlencoded" action="cart/">
		<table id="cart">
			<thead>
				<tr>
					<th>
						Название Продукта
					</th>
					<th>
						Код
					</th>
					<th>
						Количество
					</th>
					<th>
						Цена
					</th>
					<th>
						Итоговая Цена
					</th>
					<th>
						Удалить
					</th>
				</tr>
			</thead>
			<?php 
				$sum = 0;
				while($row = mysql_fetch_assoc($result)){
					$sum +=  $row["product_price"]*$_SESSION["cart"][$row["product_id"]];
					echo "<tr>
						<td><a href=\"view/". $row["product_id"] ."\">". $row["product_name"] ."<img src=\"images/product_images/tiny/". $row["image"] ."\"></a></td>
						<td>". $row["product_code_number"] ."</td>
						<td><input id=\"". $row["product_id"] ."\" name=\"". $row["product_id"] ."\" type=\"text\" value=\"". $_SESSION["cart"][$row["product_id"]] ."\"></td>
						<td>". (int)($row["product_price"])." грн" ."</td>
						<td>". $row["product_price"]*$_SESSION["cart"][$row["product_id"]]." грн" ."</td>
						<td><a href=\"index.php?route=cart/&remove=". $row["product_id"] ."\">Удалить</a></td>
						</tr>";
				}
			?>
		<tfoot>
			<tr>
				<td colspan="5">
					Общая стоимость заказа
				</td>
				<td colspan="2">
					<?php echo $sum." грн" ?>
				</td>
			</tr>
		</tfoot>
		</table>
		<input type="submit" value="Оформить заказ">
		</form>
	<?php 
	}
	else{
		echo "Корзина пуста";
	}
}

//MAKE ORDER
function CartContent(){
	if($_POST){
		if(isset($_POST["quantity"]) && $_POST["quantity"]!=""){
			//print_r($_POST);
			//add product
			if(isset($_POST["id"]) && $_POST["id"]!=""){
		   		$_POST["id"] = (int)$_POST["id"];
		   		
				if(is_int($_POST["id"])){
					$quantity = 1; 
					if(isset($_POST["quantity"]) && $_POST["quantity"]!=""){
						$quantity =	$_POST["quantity"];
					}
					if(isset($_SESSION["cart"][$_POST["id"]])){
						$_SESSION["cart"][$_POST["id"]] = $_SESSION["cart"][$_POST["id"]] + $quantity;
					}
					else{
						$_SESSION["cart"][$_POST["id"]] = $quantity;
					}
				}
				header("Location: ". domain_path ."cart/");
			}
		}
		else{
			?>
			<form id="order-contacts"  name="order-contacts" action="cart/order/" method="POST" enctype="application/x-www-form-urlencoded">
	            <label for="phone">Телефон</label>
				<input type="text" id="phone" name="phone" value="">
	           
	            <label for="email">Адрес электронной почты</label>
				<input type="text" id="email" name="email" value="">
	
	            <label for="address">Адрес доставки</label>
				<textarea id="address" name="address"></textarea>
	
	            <label for="comment">Комментарии к заказу</label>
				<textarea id="comment" name="comment"></textarea>
	
	            <input type="submit" value="Заказать!">
	        </form>
	        <?php
				foreach($_POST as $id => $quantity){
	        		$_SESSION["order"][$id] = $quantity;
				}
		}
	}
}

//SUBMIT ORDER
function OrderContent(){
	if($_POST){
		ob_start();
		ob_implicit_flush(0);
		pulseMakeTemplated("order");   
		$order_content = ob_get_contents();
		ob_end_clean();
		sendMail("pulse-ex@mail.ru", "Новый заказ", $order_content);
		
		$query = "INSERT INTO kpulse_orders SET order_content='". addslashes($order_content) ."', order_time=". time();
		$result = mysql_query($query) or die(mysql_error());
		unset($_SESSION["order"], $_SESSION["cart"]);
		echo "Заказ принят";
	}
}

function pulseMakeTemplated($type){
	if(isset($type) && $type!=""){
		switch($type){
			case "order":
				$i=0;
				foreach($_SESSION["order"] as $key => $value){
					$i++;
					if($i<2){
						$query = "SELECT product_id, product_name, product_code_number, product_price FROM kpulse_products WHERE product_id=". $key;
					}
					else{
						$query .= " UNION SELECT product_id, product_name, product_code_number, product_price FROM kpulse_products WHERE product_id=". $key;
					}
				}
				$result = mysql_query($query) or die(mysql_error());
				
			?>
				<p>
					Телефон:<?php echo $_POST["phone"]?><br/>
					Адрес электронной почты:<?php echo $_POST["email"]?><br/>
					Адрес:<?php echo $_POST["address"]?><br/>
					Комментарии:<?php echo $_POST["comment"]?><br/>
				</p>
				
				<table id="order">
					<thead>
						<tr>
							<th>
								Название Продукта
							</th>
							<th>
								Код
							</th>
							<th>
								Количество
							</th>
							<th>
								Цена
							</th>
							<th>
								Итоговая Цена
							</th>
						</tr>
					</thead>
					<?php 
						$sum = 0;
						while($row = mysql_fetch_assoc($result)){
							$sum +=  $row["product_price"]*$_SESSION["cart"][$row["product_id"]];
							echo "<tr>
								<td><a href=\"". domain_path ."view/". $row["product_id"] ."\" target=\"_blank\">". $row["product_name"] ."</a></td>
								<td>". $row["product_code_number"] ."</td>
								<td>". $_SESSION["cart"][$row["product_id"]] ."</td>
								<td>". (int)($row["product_price"])." грн" ."</td>
								<td>". $row["product_price"]*$_SESSION["cart"][$row["product_id"]]." грн" ."</td>
								</tr>";
						}
					?>
					<tfoot>
						<tr>
							<td colspan="4">
								Общая стоимость заказа
							</td>
							<td colspan="2">
								<?php echo $sum." грн" ?>
							</td>
						</tr>
					</tfoot>
			</table>
			<?php
			break;
		}	
	}
}

function sendMail($to, $subject, $message){

	$outmes = "
	<html>
	<head>
	  <title>Birthday Reminders for August</title>
	  <link rel=\"stylesheet\" href=\"". domain_path ."css/order.css\" type=\"text/css\">
	</head>
	<body>". $message ."
	</body>
	</html>";
	
	// To send HTML mail, the Content-type header must be set
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
	
	// Additional headers
	$headers .= "To: Pulse <".$to.">" . "\r\n";
	$headers .= 'From: KSE Orders <order@pulse-ex.com.ua>' . "\r\n";
	
	// Mail it
	mail($to, $subject, $message, $headers);
}
?>